import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

interface category {
    id:string|number,
    title:string
  }
import {getUserCategory} from '../../api/user'

//想在redux中异步函数中请求数据的步骤
//1.定义createAsyncThunk 2.暴露出去 组件中通过dispath（userQuery（））调用  3.在slice添加extraReducers
//在组件通过dispath时，会先到userQuery中，返回的结果当做extraReducers中函数的payload值
export const userQuery = createAsyncThunk(
    'user/query',
    async(id:number)=>{
        console.log('这是起点1')
       return await getUserCategory(id)
    }
)



//在reducer中的函数都不支持异步
const userSlice = createSlice({
    name:'user',
    initialState:{
        name:'alex',
        age:'28',
        users:<category[]>[]
    },
    reducers:{
       changeName:(state,action)=>{
        state.name = action.payload
       },
       setStateList:(state,action)=>{
          state.users = action.payload
          console.log(state.users)
       }
    },
    extraReducers:builder=>{
        builder.addCase(userQuery.fulfilled,(state,action)=>{
            console.log('这是站点2,userQuery请求回来的数据会赋值给action.payload上')
            state.users.push(action.payload)
        })
    }
})
export const {changeName,setStateList} = userSlice.actions

export default userSlice